package com.zimin.common.config;

import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.zimin.common.constant.ThreadPoolConstant;
import com.zimin.common.utils.ThreadUtil;
import org.n3r.idworker.Sid;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 公共Bean注入
 *
 * @author zimin
 * @since 2021/11/4 3:39 下午
 */
@Configuration
public class BeanConfig {


    /**
     * <p>自定义算法生成器</p>
     *
     * @since 2021-10-14 15:33:48
     */
    @Bean
    public Sid sid() {
        return new Sid();
    }

    /**
     * <p>注入公共的线程池</p>
     *
     * @return java.util.concurrent.ThreadPoolExecutor
     * @since 2021-12-21 15:21:16
     */
    @Bean(name = ThreadPoolConstant.THREAD_POOL_EXECUTOR_NAME)
    public ThreadPoolExecutor threadPoolExecutor() {
        return new ThreadPoolExecutor(ThreadPoolConstant.CORE_POOL_SIZE,
                ThreadPoolConstant.MAX_POOL_SIZE, ThreadPoolConstant.KEEP_ALIVE_SECONDS,
                TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
                r -> new Thread(r, ThreadPoolConstant.THREAD_POOL_EXECUTOR_WORKER + ThreadPoolConstant.THREAD_NUMBER.get()),
                new ThreadPoolExecutor.CallerRunsPolicy()) {
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
                ThreadUtil.exception(r, t);
            }
        };
    }

    @Bean
    public LocalDateTimeSerializer localDateTimeDeserializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
    }
}
